var express = require('express')
var bodyParser = require('body-parser')
var fs = require('fs')

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

// 使用ejs模板
app.set('views', './views')

app.set('view engine', 'ejs')

// parse application/x-www-form-urlencoded
var urlBodyParser = bodyParser.urlencoded({extended: false}) // 中间件的函数 urlencoded

// parse application/json
var jsonBodyParser = bodyParser.json()

app.get('/', function (req, res) {
    var responseJsonObj = {
        name: 'luoyal'
    }
    // res.send('this is the homepage')
    res.send(responseJsonObj)
})

// post请求
app.post('/forUrlencodedApi', urlBodyParser, function (req, res) {
    console.dir(req.body)
    res.send('Hello : ' + req.body.name)
})

app.post('/forJsonApi', jsonBodyParser, function (req, res) {
    console.dir(req.body)
    res.send('Hello : ' + req.body.name)
})


app.get('/form', function (req, res) {
    var form = fs.readFileSync('./form.html', {encoding: "utf8"})
    res.send(form)

    // sendFile 也可以渲染页面
    // res.sendFile(__dirname + '/form.html')
})

app.post('/upload', upload.single('logo'), function (req, res) {
    console.dir(req.body)
    res.send('Hello : ' + req.body.name)
})

// ejs 模板渲染
app.get('/ejsTemplate/:name', function (req, res) {
    var name = req.params.name
    res.render('form', {name: name})
})

// app.get('/ejsTemplate', function (req, res) {
//     var name = req.query.name
//     res.render('form', {name: name})
// })

// 路由
app.get('/profile/:id', function (req, res) {
    console.dir(req.params)
    res.send('You requested to see a profile page' + req.params.id)
})


app.get('/profile', function (req, res) {

    console.dir(req.query)
    res.send('profile home page : ' + req.query.find)
})


app.listen(3000)

console.log('listening to port 3000')
